/* Copyright 2011 evswork Team
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *     http://www.apache.org/licenses/LICENSE-2.0
 *  
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 */

package org.evswork.getwit;

import java.util.LinkedList;
import java.util.Queue;

import android.util.Log;

public class MessageSender {
	class Data {
		String msg;
		int retry;
		
		Data(String msg) {
			this.msg = msg;
			this.retry=0;
		}
	}
	public final static int RETRY_LIMIT=5;
	private Queue <Data> queue;
	GttMainActivity act;
	
	MessageSender(GttMainActivity act) {
		this.act = act;
		this.queue = new LinkedList<Data>();
	}
	
	private void tryPostMsg() {
		Data d=null;
		try {
			while (null != (d=queue.poll())) {
				if (d.retry > RETRY_LIMIT)
					continue;
				//act.getBotChat().sendMessage(d.msg);
			}
		} catch (Exception e) {
			if (d != null) {
				++d.retry;
				Log.e("Getwit",String.format("%s,when send\"%s\",retry=%d", e.toString(),d.msg));
				queue.offer(d);
			}
		}
	}
	
	public void postRaw(String msg) {
		try {
			//act.getBotChat().sendMessage(msg);
			return;
		} catch (Exception e) {
			Log.e("Getwit",String.format("%s,when send\"%s\"", e.toString(),msg));
		}
		Data d = new Data(msg);
		if (!queue.contains(d)) {
			queue.offer(d);
		}
		
	}
	
	public void notifyConnected() {
		tryPostMsg();
	}
}
